package com.blog4j.server.modules.email.core;

import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.server.modules.email.context.EmailContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/14 12:34
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class EmailEngineImpl extends AbstractEmailEngine {
    private final JavaMailSender javaMailSender;

    @Override
    protected void doSendNoticeEmail(EmailContext emailContext) {

    }

    @Override
    protected void doSendSystemEmail(EmailContext emailContext) {
        String content = emailContext.getContent();
        String email = emailContext.getEmail();
        String subject = emailContext.getSubject();
        String from = emailContext.getFrom();
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mineHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置邮件主题
            mineHelper.setSubject(subject);
            // 设置邮件发送者
            mineHelper.setFrom(from);
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开
            mineHelper.setTo(email);
            // 设置邮件发送日期
            mineHelper.setSentDate(new Date());
            // 设置邮件的正文
            mineHelper.setText(content,true);
            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException exception) {
            throw new Blog4jException(ErrorEnum.SEND_EMAIL_ERROR);
        }
    }
}
